package com.gofaraway.common.util;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.gofaraway.common.enums.OssContentTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Locale;

/**
 * @author ChenPeng
 * @Date 2024/5/15 17:49
 */
@Component
@Slf4j
public class OssUtils {

    //@Value("${cloud-transport-carrier-portal-ak}")
    private String accessKeyId = "LTAI4G1gQTPRHvQpyVnon8qh";

    //@Value("${cloud-transport-carrier-portal-sk}")
    private String accessKeySecret = "Jfm8mtvtVbiPyRTVzsaHu7rRSYx9Jz";

    //@Value("${tms.endpoint}")
    private String tmsEndpoint = "https://oss-cn-shanghai.aliyuncs.com";

    //@Value("${tms.bucketName}")
    private String bucketName = "sto-transport-tms";


    public static final String YYYYMMDDHHMMSS2 = "yyyyMMddHHmmss";

    /**
     * @param inputStream 图片文件
     * @param fileName    图片名称
     * @return
     */
    public String uploadOssFile(InputStream inputStream, String fileName, OssContentTypeEnum typeEnum) {
        OSS oss = new OSSClientBuilder().build(tmsEndpoint, accessKeyId, accessKeySecret);
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(typeEnum.getName());
            objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);

            String fileKey = fileName + DateUtil.format(new Date(), YYYYMMDDHHMMSS2) + typeEnum.getCode();
            oss.putObject(bucketName, fileKey, inputStream, objectMetadata);
            // 设置URL过期时间为20年
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 20);
            URL picUrl = oss.generatePresignedUrl(bucketName, fileKey, expiration);
            // 设置访问路径
            String fileUrl = picUrl.toString().split("\\?")[0];
            log.info("oss文件访问路径:{}", fileUrl);
            return fileUrl;
        } catch (Exception e) {
            log.error("transferInputStreamToOssUrl error:{}", JSON.toJSONString(e));
        } finally {
            oss.shutdown();
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                log.error("OssUtils. 关闭输入流出错:{}", JSON.toJSONString(e));
            }
        }
        return null;
    }
}
